class Snake {
  head: HTMLElement;
  bodys: HTMLCollection;
  element: HTMLElement;

  constructor() {
    this.element = document.getElementById("snake")!;
    this.head = document.querySelector("#snake>div") as HTMLElement;
    this.bodys = this.element.getElementsByTagName("div");
  }

  get X() {
    return this.head.offsetLeft;
  }
  get Y() {
    return this.head.offsetTop;
  }
  set X(value: number) {
    if (this.X == value) {
      return;
    }
    if (value < 0 || value > 290) {
      throw new Error("蛇撞墙了!");
    }

    

   this.moveBody()
    this.head.style.left = value + "px";
  }
  set Y(value: number) {
    if (this.Y == value) {
      return;
    }
    if (value < 0 || value > 290) {
      throw new Error("蛇撞墙了!");
    }
    this.moveBody()
    this.head.style.top = value + "px";
  }
  addBdy() {
    this.element.insertAdjacentHTML("beforeend", "<div></div>");
  }
  moveBody() {
    for (let i = this.bodys.length - 1; i > 0; i--) {
      let X = (this.bodys[i - 1] as HTMLElement).offsetLeft;
      let Y = (this.bodys[i - 1] as HTMLElement).offsetTop;
      (this.bodys[i] as HTMLElement).style.left = X + "px";
      (this.bodys[i] as HTMLElement).style.top = Y + "px";
    }
  }
}

export default Snake;
